﻿using System;
using System.ComponentModel;
using BIStudio.Framework.Utils;
using StackExchange.Redis;

namespace BIStudio.Framework.Cache
{
    /// <summary>
    ///     远程缓存管理器
    /// </summary>
    [Description("Redis")]
    public class RedisCacheProvider : ICache
    {
        private readonly IDatabase _client;

        public RedisCacheProvider()
        {
            string server = string.IsNullOrEmpty(ALConfig.AppSettings["CacheServer"]) ? "127.0.0.1" : ALConfig.AppSettings["CacheServer"];
            int port = Convert.ToInt32(string.IsNullOrEmpty(ALConfig.AppSettings["CachePort"]) ? "6379" : ALConfig.AppSettings["CachePort"]);
            _client = ConnectionMultiplexer.Connect(server + ":" + port).GetDatabase();
        }

        public void Add<T>(string hashKey, T value, int cacheMinutes)
        {
            _client.StringSet(hashKey, ALSerialize.JsonSerialize(value), new TimeSpan(0, cacheMinutes, 0));
        }

        public T Get<T>(string hashKey)
        {
            if (_client.KeyExists(hashKey))
                return ALSerialize.JsonDeserialize<T>(_client.StringGet(hashKey).ToString());
            else
                return default(T);
        }
        public void Remove(string hashKey)
        {
            _client.KeyDelete(hashKey);
        }

        public void Clear(string prefix)
        {
            _client.KeyDelete(prefix + "*");
        }

        public bool Contains(string hashKey)
        {
            return _client.KeyExists(hashKey);
        }
    }
}